/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the GPL
 * version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.actions;

import org.digitalsoul.switchplugin.model.ISwitchFile;

public abstract class MatchReplacementAction extends Action {

    private static final String ARROW = " => ";
    private final String replace;
    private final String match;
    private final boolean executeOnce;

    /**
     * @param matchRegex a regular expression to match the part that gets replaced
     * @param replacement the string which is used to replace the matched region
     * @param executeOnce if true multiple matches will be replaced
     */
    private MatchReplacementAction(String matchRegex, String replacement, boolean executeOnce) {
        this.match = matchRegex;
        this.replace = replacement;
        this.executeOnce = executeOnce;
    }

    /**
     * @param matchRegex a regular expression to match the part that gets replaced
     * @param replacement the string which is used to replace the matched region
     */
    public MatchReplacementAction(String matchRegex, String replacement) {
        this(matchRegex, replacement, true);
    }

    @Override
    public ISwitchFile applyAction(ISwitchFile file) {
        String path = getFilePart(file);
        if (!executeOnce) {
            while (path.matches(match)) {
                path = path.replaceAll(match, replace);
            }
        }
        else {
            path = path.replaceFirst(match, replace);
        }
        file = applyToFile(file, path);
        return file;
    }

    protected abstract String getFilePart(ISwitchFile file);

    protected abstract ISwitchFile applyToFile(ISwitchFile file, String string);

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(match);
        buffer.append(ARROW);
        buffer.append(replace);
        return buffer.toString();
    }
}
